﻿using System;
using System.Collections.Generic; // gerir notkun á sniðmátum möguleg
using System.Linq;
using System.Web;

/*
* University of Reykjavík
* Brjóstagjöf.is is the product of first-year practical programming course
* for computer science students at said university
*
* URL: http://code.google.com/p/scags 
* Authors: 
* Ástvaldur Sigurðsson
* Guðjón Jónsson
* Kristín Inga Vigfúsdóttir
* Steinar Bragi Sigurðsson
* Sveinn Ernstsson
*/
namespace skags.Models
{
    /*
    * Samskipti við töflur Page, SubPage og PageCategory í gagnagrunni
    */
    public class PageRepository
    {
        // tilvik af gagnagrunni (vísun/tenging í gagnagrunn) búin til
        DBDataContext _dc = new DBDataContext();

        // Vistar breytingar
        public void Save()
        {
            _dc.SubmitChanges();
        }

        /*
         * Ná í allar síður og undirsíður
         */ 
        public PageTablesViewModel GetAll()
        {
            var allPage = from s in _dc.Pages
                          orderby s.ID descending
                          select s;

            var allCategories = from s in _dc.PageCategories
                                orderby s.Title ascending
                                select s;

            return new PageTablesViewModel { Pages = allPage, Categories = allCategories };
        }

        /*
         * Ná í allar síður og undirsíður.
         * Notað af AdminController.
         */ 
        public IEnumerable<PageViewModel> GetAllPages()
        {
            var result = from a in _dc.Pages
                         join u in _dc.aspnet_Users on a.CreatorID equals u.UserId
                         where a.SubPage == false
                         orderby a.ParentID, a.ID ascending
                         select new PageViewModel
                         {
                             ID = a.ID,
                             Title = a.Title,
                             CreatorID = a.CreatorID,
                             CreatorName = u.UserName,
                             DateCreated = a.DateCreated,
                             Text = a.Text,
                             ParentID = a.ParentID,
                             ParentName = ( a.SubPage == false ? _dc.PageCategories.Where(s=>s.ID == a.ParentID).SingleOrDefault().Title : _dc.Pages.Where(s=>s.ID == a.ParentID).SingleOrDefault().Title),
                             SubPage = a.SubPage,
                             SubPages = (from s in _dc.Pages
                                        where s.SubPage == true && s.ParentID == a.ID
                                        orderby s.ID ascending
                                        select new SubPageViewModel
                                        {
                                                ID = s.ID,
                                                Title = s.Title,
                                                CreatorID = s.CreatorID,
                                                CreatorName = _dc.aspnet_Users.Where(au=>au.UserId == s.CreatorID).SingleOrDefault().UserName,
                                                DateCreated = s.DateCreated,
                                                Text = s.Text,
                                                ParentID = s.ParentID,
                                                ParentName = a.Title
                                        })
                         };

            return result;
        }
        /*
         * Saekir allar síður eftir yfirflokkum.
         * Notað af HomeController.
         */
        public IEnumerable<PageViewModel> GetAllPagesByCategory(int catid)
        {
            var result = from a in _dc.Pages
                         join u in _dc.aspnet_Users on a.CreatorID equals u.UserId
                         where a.SubPage == false && a.ParentID == catid
                         orderby a.ID ascending
                         select new PageViewModel
                         {
                             ID = a.ID,
                             Title = a.Title,
                             CreatorID = a.CreatorID,
                             CreatorName = u.UserName,
                             DateCreated = a.DateCreated,
                             Text = a.Text,
                             ParentID = a.ParentID,
                             ParentName = (a.SubPage == false ? _dc.PageCategories.Where(s => s.ID == a.ParentID).SingleOrDefault().Title : _dc.Pages.Where(s => s.ID == a.ParentID).SingleOrDefault().Title),
                             SubPage = a.SubPage,
                             SubPages = (from s in _dc.Pages
                                         where s.SubPage == true && s.ParentID == a.ID
                                         orderby s.ID ascending
                                         select new SubPageViewModel
                                         {
                                             ID = s.ID,
                                             Title = s.Title,
                                             CreatorID = s.CreatorID,
                                             CreatorName = _dc.aspnet_Users.Where(au => au.UserId == s.CreatorID).SingleOrDefault().UserName,
                                             DateCreated = s.DateCreated,
                                             Text = s.Text,
                                             ParentID = s.ParentID,
                                             ParentName = a.Title
                                         })
                         };

            return result;
        }

        /*
         * Ná í allar yfirsíður
         * Notað af AdminController.
         */
        public IEnumerable<PageCategoryViewModel> GetAllPageCategories(bool subpage, int? pageid)
        {
            IEnumerable<PageCategoryViewModel> allCategories;

            if (subpage)
            {
                allCategories = (from s in _dc.Pages
                                 where s.SubPage == false
                                 select new PageCategoryViewModel
                                 {
                                     ID = s.ID,
                                     Title = s.Title
                                 });
            }
            else
            {
                allCategories = (from s in _dc.PageCategories
                                 select new PageCategoryViewModel
                                 {
                                     ID = s.ID,
                                     Title = s.Title
                                 });
            }

            return allCategories;
        }

        /*
         * Saekir síðu eftir númeri
         * Notað af AdminController.
         */
        public Page GetPageByID(int id)
        {
            return _dc.Pages.SingleOrDefault(u => u.ID == id);
        }

        /*
         * Saekir titil eftir foreldrisnúmeri
         * Notað af AdminController.
         */
        public string GetTitleByParentID(int parentID)
        {
            return _dc.Pages.Where(s => s.ID == parentID).SingleOrDefault().Title;
        }

        /*
         * Athugar hvort síða sé undirsíða
         * Notað af AdminController.
         */
        public bool IsSubPage(int? id)
        {
            if (!id.HasValue)
                return false;

            return _dc.Pages.Where(s => s.ID == id.Value && s.SubPage == false).Count() > 0;
        }

        /* 
         * Býr til síðu
         * Notað af AdminController.
         */ 
        public void AddPage(Page item)
        {
            _dc.Pages.InsertOnSubmit(item);
            Save();
        }

        /* 
         * Uppfærir síðu
         * Notað af AdminController.
         */ 
        public void UpdatePage(Page item)
        {
            var thePage = GetPageByID(item.ID);
            if (thePage != null)
            {
                thePage.ParentID = item.ParentID;
                thePage.Text = item.Text;
                thePage.Title = item.Title;

                Save();
            }
        }

        /* 
         * Eyðir síðu og undirsíðum undir henni
         * Notað af AdminController.
         */ 
        public void DeletePage(int id)
        {
            var itemToDelete = GetPageByID(id);

            if( itemToDelete == null )
                throw new Exception("Síðan sem þú reynir að eyða er ekki til!");

            var childitemToDelete = _dc.Pages.Where(s => s.ParentID == id || s.ID == id);

            _dc.Pages.DeleteAllOnSubmit(childitemToDelete);

            Save();
        }
    }
}